{%extends 'dbmp_base.html' %}

{% load staticfiles %}
{% load ip_filters %}
{% load filters_dbmp_mysql_instance %}

<!-- 添加该页面自己需要的 css 模板 -->
{% block css %}
    <link href="{% static 'css/plugins/footable/footable.core.css' %}" rel="stylesheet">
    <link href="{% static 'css/plugins/sweetalert/sweetalert.css' %}" rel="stylesheet">
{% endblock %}


<!-- 显示该页面标题 -->
{% block app_title %}MySQL实例列表{% endblock %}

<!-- 其他元素模块 -->
{% block top_element %}
<!-- 添加MySQL实例按钮 -->
<div class="row fontawesome-icon-list">
    <div class="fa-hover col-md-2 col-sm-3 pull-right">
        <a href="{% url 'dbmp_mysql_instance_add' %}">
            <i class="fa fa-plus-square"></i>
            添加实例
        </a>
    </div>
</div>
{% endblock %}

<!-- 显示该页面主要展示的内容 -->
{% block content %}
<table class="footable table table-stripped toggle-arrow-tiny table-hover">
    <thead>
        <tr>
            <th class="text-center">#</th>
            <th class="text-center">Host</th>
            <th class="text-center">Port</th>
            <th class="text-center">用户名</th>
            <th class="text-center col-xs-1">密码</th>
            <th class="text-center col-xs-1">运行状态</th>
            <th class="text-center col-xs-3">操作</th>
            <th data-hide="all">更多操作</th>
        </tr>
    </thead>

    <tbody>
        {% for dbmp_mysql_instance in pagination.objs %}
        <tr>
            <td class="text-center">{{ forloop.counter }}</td>
            <td class="text-center">{{ dbmp_mysql_instance.host | f_num2ip }}</td>
            <td class="text-center">{{ dbmp_mysql_instance.port }}</td>
            <td class="text-center">{{ dbmp_mysql_instance.username }}</td>
            <td class="text-center">
                <a title="{{ dbmp_mysql_instance.password }}"
                       data-toggle="password" data-placement="top">
                    <i class="fa fa-thumb-tack"></i>
                    悬停显示
                </a>
            </td>
            <td class="text-center">
                <span id="run_status_{{ dbmp_mysql_instance.mysql_instance_id }}"
                      class="label label-{{ dbmp_mysql_instance.run_status | f_run_status_color }}
                             run_status_cls">
                    <input type="hidden" class="run_status_value_cls" 
                           value="{{ dbmp_mysql_instance.run_status }}">
                    <input type="hidden" class="mysql_instance_id_value_cls" 
                           value="{{ dbmp_mysql_instance.mysql_instance_id }}">
                    {{ dbmp_mysql_instance.run_status | f_run_status }}
                </span>
            </td>
            <td class="text-center">
                <a onclick="dbmp_mysql_instance_delete({{ dbmp_mysql_instance.mysql_instance_id }}, {{ pagination.cur_page }})"
                   type="button" class="btn btn-danger">
                    <i class="fa fa-trash"></i>
                    删除
                </a>
                <a href="{% url 'dbmp_mysql_instance_edit' %}?mysql_instance_id={{ dbmp_mysql_instance.mysql_instance_id }}" 
                   type="button" class="btn btn-primary">
                    <i class="fa fa-edit"></i>
                    编辑
                </a>
                <a href="{% url 'dbmp_mysql_instance_view' %}?mysql_instance_id={{ dbmp_mysql_instance.mysql_instance_id }}" 
                   type="button" class="btn btn-info">
                    <i class="fa fa-eye"></i>
                    查看
                </a>
            </td>
            <td class="text-center">
                <button type="button" id="terminal_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        class="more_btn btn btn-info btn-xs {% if dbmp_mysql_instance.run_status == 2 %}btn-outline{% endif %}"
                        onclick="terminal_sql_console({{ dbmp_mysql_instance.mysql_instance_id }})"
                        {% if dbmp_mysql_instance.run_status != 2 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-terminal"></i>
                    命令窗口
                </button>
                <button type="button" id="backup_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        class="more_btn btn btn-success btn-xs {% if dbmp_mysql_instance.run_status == 2 %}btn-outline{% endif %}"
                        {% if dbmp_mysql_instance.run_status != 2 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-cubes"></i>
                    设置备份
                </button>
                <button type="button" id="polling_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        class="more_btn btn btn-success btn-xs {% if dbmp_mysql_instance.run_status == 2 %}btn-outline{% endif %}"
                        {% if dbmp_mysql_instance.run_status != 2 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-cogs"></i>
                    巡检报告
                </button>


                <button type="button" id="stop_instance_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        onclick="stop_mysql_instance({{ dbmp_mysql_instance.mysql_instance_id }}, '{{ dbmp_mysql_instance.host | f_num2ip }}', {{ dbmp_mysql_instance.port }}, this)"
                        class="more_btn btn btn-danger btn-xs {% if dbmp_mysql_instance.run_status == 2 %}btn-outline{% endif %}"
                        {% if dbmp_mysql_instance.run_status != 2 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-power-off"></i>
                    关闭实例
                </button>
                <button type="button" id="start_instance_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        onclick="start_mysql_instance({{ dbmp_mysql_instance.mysql_instance_id }}, '{{ dbmp_mysql_instance.host | f_num2ip }}', {{ dbmp_mysql_instance.port }}, this)"
                        class="more_btn btn btn-danger btn-xs {% if dbmp_mysql_instance.run_status == 1 %}btn-outline{% endif %}
                               start_instance_cls"
                        {% if dbmp_mysql_instance.run_status != 1 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-caret-square-o-right"></i>
                    启动实例
                </button>


                <button type="button" id="restart_instance_{{ dbmp_mysql_instance.mysql_instance_id }}"
                        onclick="restart_mysql_instance({{ dbmp_mysql_instance.mysql_instance_id }}, '{{ dbmp_mysql_instance.host | f_num2ip }}', {{ dbmp_mysql_instance.port }}, this)"
                        class="more_btn btn btn-danger btn-xs {% if dbmp_mysql_instance.run_status == 1 or dbmp_mysql_instance.run_status == 2 or dbmp_mysql_instance.run_status == 3 %}btn-outline{% endif %}"
                        {% if dbmp_mysql_instance.run_status != 1 and dbmp_mysql_instance.run_status != 2 and dbmp_mysql_instance.run_status != 3 %}disabled="disabled"{% endif %}>
                    <i class="fa fa-refresh"></i>
                    重启实例
                </button>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

<!-- 这里是分页页码 -->
<div class="btn-group">
    <!-- 第一页, 上一页 -->
    {% if pagination.cur_page != 1 and pagination %}
        <a type="button" class="btn btn-primary btn-outline" href="?cur_page=1">
            <i class="fa fa-angle-double-left"></i>
        </a>
        <a type="button" class="btn btn-primary btn-outline" href="?cur_page={{ pagination.pre_page }}">
            <i class="fa fa-angle-left"></i>
        </a>
    {% endif %}
    
    <!-- 省略号 -->
    {% if pagination.start_page_omit_symbol %}
        <a type="button" class="btn btn-write btn-outline">
            <i class="fa fa-ellipsis-h"></i>
        </a>
    {% endif %}
    
    <!-- 能点击的页码 -->
    {% for page_item in pagination.page_items %}
        {% if page_item == pagination.cur_page %}
            <a type="button" class="btn btn-primary">{{ page_item }}</a>
        {% else %}
            <a type="button" class="btn btn-primary btn-outline" href="?cur_page={{ page_item }}">{{ page_item }}</a>
        {% endif %}
    {% endfor%}
    
    <!-- 省略号 -->
    {% if pagination.end_page_omit_symbol %}
        <a type="button" class="btn btn-write btn-outline">
            <i class="fa fa-ellipsis-h"></i>
        </a>
    {% endif %}
    
    <!-- 下一页, 最后一页 -->
    {% if pagination.cur_page != pagination.all_page and pagination %}
        <a type="button" class="btn btn-primary btn-outline" href="?cur_page={{ pagination.next_page }}">
            <i class="fa fa-angle-right"></i>
        </a>
        <a type="button" class="btn btn-primary btn-outline" href="?cur_page={{ pagination.all_page }}">
            <i class="fa fa-angle-double-right"></i>
        </a>
    {% endif %}
</div>
{% endblock %}

<!-- 添加该页面自己需要的 js 模板 -->
{% block js %}
    <script src="{% static 'js/content.min.js' %}"></script>
    <script src="{% static 'js/plugins/footable/footable.all.min.js' %}"></script>
    <script src="{% static 'js/plugins/sweetalert/sweetalert.min.js' %}"></script>
    <script src="{% static 'js/plugins/layer/layer.min.js' %}"></script>

    <script>
        // 使用 Django csrf 功能
        $.ajaxSetup({headers: {"X-CSRFToken": '{{ csrf_token }}'}});

        $(document).ready(function(){
            // 表格插件
            $(".footable").footable();

            // 显示密码
            $("[data-toggle='password']").tooltip();

            // 检测MySQL状态
            $(".run_status_cls").each(function (i){
                run_status = $(this).find(".run_status_value_cls").val();
                mysql_instance_id = $(this).find(".mysql_instance_id_value_cls").val();
     
                if(run_status == 1) { // 停止
                    check_start_mysql(mysql_instance_id);
                } else if(run_status == 2) { // 正常运行
                    check_start_mysql(mysql_instance_id);
                } else if(run_status == 3) { // 未知
                    check_start_mysql(mysql_instance_id);
                } else if(run_status == 4) { // 正在启动
                    check_start_mysql(mysql_instance_id);
                } else if(run_status == 5) { // 正在停止
                    check_start_mysql(mysql_instance_id);
                }
            });
        });

        // 打开执行SQL命令行窗口
        function terminal_sql_console(mysql_instance_id) {
            url = "";
            url += "{% url 'dbmp_mysql_instance_terminal_sql_console' %}";
            url += "?mysql_instance_id=" + mysql_instance_id;
            open_iframe_window("sql窗口", url);
        }

        // 打开一个 iframe 窗口
        function open_iframe_window(tab_name, url) {
            var timestamp = (new Date()).valueOf(); 
            iframe_name = "name" + timestamp;

            // iframe 菜单 标签
            iframe_tab = '';
            iframe_tab += '<a href="javascript:;" class="active J_menuTab" ';
            iframe_tab += 'data-id="'+ timestamp +'">' + tab_name;
            iframe_tab += '<i class="fa fa-times-circle"></i>';
            iframe_tab += '</a>';

            // iframe 内容
            iframe_content = '';
            iframe_content += '<iframe class="J_iframe" name="'+ iframe_name +'" width="100%" height="100%" ';
            iframe_content += 'src="' + url + '" frameborder="0" ';
            iframe_content += 'data-id="'+ timestamp +'" seamless style="display: inline;">';
            iframe_content += '</iframe>';

            // 打开标签和 iframe
            $(".page-tabs .page-tabs-content .J_menuTab", parent.document).removeClass('active');
            $(".page-tabs .page-tabs-content", parent.document).append(iframe_tab);
            $("#content-main .J_iframe", parent.document).css('display','none'); 
            $("#content-main", parent.document).append(iframe_content);
        }

        //删除 dbmp_mysql_instance
        function dbmp_mysql_instance_delete(mysql_instance_id, cur_page) {
            $(".confirm").unbind("click");
            swal({
                title: "您确定要删除这条信息吗?",
                text: "删除后将无法恢复，请谨慎操作！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "删除",
                closeOnConfirm: false
            }, function () {
                $.ajax({
                    url: "{% url 'dbmp_mysql_instance_ajax_delete' %}",
                    type: "POST",
                    dataType: "json",
                    data: {
                        mysql_instance_id: mysql_instance_id
                    }
                }).done(function(data) { 
                    if(data == true) {
                        swal("删除成功!", "已成功删除数据！", "success");
                        $(".confirm").click(function(){
                            setTimeout("location.reload()", 500);
                        });
                    } else {
                        swal("对不起!", "删除数据失败了!", "error");
                    }
                }).error(function(data) { 
                    swal("对不起!", "删除操作失败了(调用删除方法失败)!", "error");
                });
            });
        }

        function start_mysql_instance(mysql_instance_id, mysql_host,
                                      mysql_port, obj) {
            // 获得MySQL 启动、关闭、重启 警告信息
            text = start_mysql_warning_text(mysql_host, mysql_port);
            swal({
                title: "确定(启动)MySQL实例？",
                text: text,
                type: "warning",
                html: true,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function () {
                swal({
                    title: "启动MySQL中...",
                    text: "",
                    timer: 1,
                    showConfirmButton: false 
                });
                // 禁用该实例的其他按钮
                $(obj).removeClass("btn-outline");
                $(obj).attr({disabled: "disabled"});
                $(obj).siblings().removeClass("btn-outline");
                $(obj).siblings().attr({disabled: "disabled"});

                // 修改状态
                $("#run_status_" + mysql_instance_id).removeClass(function(index, css){
                    return (css.match (/\blabel-\S+/g) || []).join(' ');
                });
                $("#run_status_" + mysql_instance_id).addClass("label-{{ 5 | f_run_status_color }}");
                $("#run_status_" + mysql_instance_id).html("{{ 5 | f_run_status }}");

                // 点击启动按钮打开一个新的iframe命令窗口
                index = layer.open({
                    type: 2,
                    title: "启动MySQL实例命令窗口",
                    shadeClose: true,
                    shade: false, // 没有遮罩
                    offset: "rb", // 左下角弹框
                    maxmin: true,
                    shift: 2,
                    shadeClose: true, //点击遮罩关闭层
                    area : ["100%" , "40%"], // 弹窗大小
                    moveOut: false, // 不可以在窗口外拖拽
                    content: "{% url 'dbmp_mysql_instance_start_instance_terminal' %}?mysql_instance_id=" + mysql_instance_id
                });
            });
        }

        function stop_mysql_instance(mysql_instance_id, mysql_host,
                                      mysql_port, obj) {
            // 获得MySQL 启动、关闭、重启 警告信息
            text = start_mysql_warning_text(mysql_host, mysql_port);
            swal({
                title: "确定(关闭)MySQL实例？",
                text: text,
                type: "warning",
                html: true,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function () {
                swal({
                    title: "关闭MySQL中...",
                    text: "",
                    timer: 1,
                    showConfirmButton: false 
                });
                // 禁用该实例的其他按钮
                $(obj).removeClass("btn-outline");
                $(obj).attr({disabled: "disabled"});
                $(obj).siblings().removeClass("btn-outline");
                $(obj).siblings().attr({disabled: "disabled"});

                // 修改状态
                $("#run_status_" + mysql_instance_id).removeClass(function(index, css){
                    return (css.match (/\blabel-\S+/g) || []).join(' ');
                });
                $("#run_status_" + mysql_instance_id).addClass("label-{{ 4 | f_run_status_color }}");
                $("#run_status_" + mysql_instance_id).html("{{ 4 | f_run_status }}");

                // 点击启动按钮打开一个新的iframe命令窗口
                index = layer.open({
                    type: 2,
                    title: "启动MySQL实例命令窗口",
                    shadeClose: true,
                    shade: false, // 没有遮罩
                    offset: "rb", // 左下角弹框
                    maxmin: true,
                    shift: 2,
                    shadeClose: true, //点击遮罩关闭层
                    area : ["100%" , "40%"], // 弹窗大小
                    moveOut: false, // 不可以在窗口外拖拽
                    content: "{% url 'dbmp_mysql_instance_stop_instance_terminal' %}?mysql_instance_id=" + mysql_instance_id
                });
            });
        }

        function restart_mysql_instance(mysql_instance_id, mysql_host,
                                      mysql_port, obj) {
            // 获得MySQL 启动、关闭、重启 警告信息
            text = start_mysql_warning_text(mysql_host, mysql_port);
            swal({
                title: "确定(重启)MySQL实例？",
                text: text,
                type: "warning",
                html: true,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function () {
                swal({
                    title: "重启MySQL中...",
                    text: "",
                    timer: 1,
                    showConfirmButton: false 
                });
                // 禁用该实例的其他按钮
                $(obj).removeClass("btn-outline");
                $(obj).attr({disabled: "disabled"});
                $(obj).siblings().removeClass("btn-outline");
                $(obj).siblings().attr({disabled: "disabled"});

                // 修改状态
                $("#run_status_" + mysql_instance_id).removeClass(function(index, css){
                    return (css.match (/\blabel-\S+/g) || []).join(' ');
                });
                $("#run_status_" + mysql_instance_id).addClass("label-{{ 4 | f_run_status_color }}");
                $("#run_status_" + mysql_instance_id).html("{{ 4 | f_run_status }}");

                // 点击启动按钮打开一个新的iframe命令窗口
                index = layer.open({
                    type: 2,
                    title: "启动MySQL实例命令窗口",
                    shadeClose: true,
                    shade: false, // 没有遮罩
                    offset: "rb", // 左下角弹框
                    maxmin: true,
                    shift: 2,
                    shadeClose: true, //点击遮罩关闭层
                    area : ["100%" , "40%"], // 弹窗大小
                    moveOut: false, // 不可以在窗口外拖拽
                    content: "{% url 'dbmp_mysql_instance_restart_instance_terminal' %}?mysql_instance_id=" + mysql_instance_id
                });
            });
        }

        // 当状态为正在启动时检测MySQL状态
        function check_start_mysql(mysql_instance_id) {
            // 对MySQL进行检测
            $.ajax({
                url: "{% url 'dbmp_mysql_handler_ajax_mysql_instance_status' %}",
                type: "POST",
                dataType: "json",
                data: {
                    mysql_instance_id: mysql_instance_id
                }
            }).done(function(data) { 
                if(data == 2) { // 启动成功
                    start_mysql_success_css(mysql_instance_id);
                } else if(data == 1) { // 启动失败
                    start_mysql_fail_css(mysql_instance_id);
                } else if(data == 3) { // 还在启动
                    // 暂时不做处理
                    console.log("还在启动");
                } else { // data == 4 检测失败
                    // 暂时不做处理
                    console.log("检测失败 data: " + data);
                }
            }).error(function(data) { // 执行检测失败，内部错误
                // 暂时不做处理
                console.log("执行检测失败，内部错误");
            }); 
        }

        // 当检测到MySQL没有启动 修改为停止状态的CSS
        function start_mysql_fail_css(mysql_instance_id) {
            // 添加可点击css
            $("#start_instance_" + mysql_instance_id).addClass("btn-outline");
            $("#restart_instance_" + mysql_instance_id).addClass("btn-outline");
            $("#stop_instance_" + mysql_instance_id).removeClass("btn-outline");
            $("#terminal_" + mysql_instance_id).removeClass("btn-outline");
            $("#backup_" + mysql_instance_id).removeClass("btn-outline");
            $("#polling_" + mysql_instance_id).removeClass("btn-outline");

            $("#start_instance_" + mysql_instance_id).removeAttr("disabled");
            $("#restart_instance_" + mysql_instance_id).removeAttr("disabled");
            $("#stop_instance_" + mysql_instance_id).attr({disabled: "disabled"});
            $("#terminal_" + mysql_instance_id).attr({disabled: "disabled"});
            $("#backup_" + mysql_instance_id).attr({disabled: "disabled"});
            $("#polling_" + mysql_instance_id).attr({disabled: "disabled"});
            
            // 修改状态
            $("#run_status_" + mysql_instance_id).removeClass(function(index, css){
                return (css.match (/\blabel-\S+/g) || []).join(' ');
            });
            $("#run_status_" + mysql_instance_id).addClass("label-{{ 1 | f_run_status_color }}");
            $("#run_status_" + mysql_instance_id).html("{{ 1 | f_run_status }}");
        }

        // 当检测到MySQL启动成功 修改为运行中状态的CSS
        function start_mysql_success_css(mysql_instance_id) {
            // 添加可点击css
            $("#stop_instance_" + mysql_instance_id).addClass("btn-outline");
            $("#restart_instance_" + mysql_instance_id).addClass("btn-outline");
            $("#terminal_" + mysql_instance_id).addClass("btn-outline");
            $("#backup_" + mysql_instance_id).addClass("btn-outline");
            $("#polling_" + mysql_instance_id).addClass("btn-outline");

            $("#stop_instance_" + mysql_instance_id).removeAttr("disabled");
            $("#restart_instance_" + mysql_instance_id).removeAttr("disabled");
            $("#terminal_" + mysql_instance_id).removeAttr("disabled");
            $("#backup_" + mysql_instance_id).removeAttr("disabled");
            $("#polling_" + mysql_instance_id).removeAttr("disabled");
            
            // 修改状态
            $("#run_status_" + mysql_instance_id).removeClass(function(index, css){
                return (css.match (/\blabel-\S+/g) || []).join(' ');
            });
            $("#run_status_" + mysql_instance_id).addClass("label-{{ 2 | f_run_status_color }}");
            $("#run_status_" + mysql_instance_id).html("{{ 2 | f_run_status }}");
        }

        // MySQL 启动，关闭，重启 操作的提示警告
        function start_mysql_warning_text(mysql_host, mysql_port) {
            text = '';
            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp;MySQL 连接: <code class="text-primary">' + mysql_host + '</code>';
            text += '</div>';

            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp;MySQL 端口: <code class="text-primary">' + mysql_port + '</code>';
            text += '</div>';

            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp; 启动、关闭、重启 MySQL 是一件很重要的，请谨慎操作';
            text += '</div>';

            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp; 1.在做类似操作时请与开发、运维、DBA等相关人员沟通确认，从而避免一些不必要的问题发生。';
            text += '</div>';
            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp; 2.如果是宕机后的启动，最好先确认宕机的原因再启动';
            text += '</div>';
            text += '<div class="row text-left">';
            text += '&nbsp;&nbsp;&nbsp;&nbsp; 3.关闭和重启操作请再三确认';
            text += '</div>';
            return text;
        }

    </script>
{% endblock %}
